/**
 * Copyright (c) 2005-2012 https://github.com/zhangkaitao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.shine.extra.exception.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.shine.common.utils.LogUtils;
import com.shine.common.web.utils.HttpUtils;
import com.shine.extra.exception.web.entity.ExceptionResponse;


@ControllerAdvice
public class DefaultExceptionHandler {
	
	//@ResponseStatus(reason="运行时异常", value=HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler({RuntimeException.class})
	public ModelAndView processRuntimeException(HttpServletRequest request, HttpServletResponse response, Exception e) {
		LogUtils.logError("运行时异常", e);
		
		ExceptionResponse exceptionResponse = ExceptionResponse.from(e);
		
		ModelAndView mv = new ModelAndView();
		mv.addObject("error", exceptionResponse);
		
		//如果设置了@ResponseStatus，该处不起作用了，将由web.xml文件中配置的500进行拦截
		mv.setViewName("error/exception"); 
		
		return mv;
	}

	//@ResponseStatus(reason="用户权限验证失败",value=HttpStatus.UNAUTHORIZED)
	@ExceptionHandler({UnauthorizedException.class})
    public ModelAndView processUnauthenticatedException(HttpServletRequest request, UnauthorizedException e) {
    	LogUtils.logError("用户权限验证失败", e);
    	
        ExceptionResponse exceptionResponse = ExceptionResponse.from(e);

        ModelAndView mv = new ModelAndView();
        mv.addObject("error", exceptionResponse);
        
        //如果设置了@ResponseStatus，该处不起作用了，将由web.xml文件中配置的401进行拦截
        mv.setViewName("error/401");	

        return mv;
    }

	
	
	
	public void ajaxRequest(ExceptionResponse exceptionResponse, HttpServletRequest request, HttpServletResponse response) {
		if(HttpUtils.isAjaxReqeuest(request)) {
			try {
				response.setContentType("application/json;charset=utf-8");
				response.setStatus(500);
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(exceptionResponse)) ;
				out.flush();
				out.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	

}
